package cc.rengu.redp.hawk.controller;


import cc.rengu.redp.hawk.domain.GraphData;
import cc.rengu.redp.hawk.domain.GraphDataQuery;
import cc.rengu.redp.hawk.domain.HawkMonitorShow;
import cc.rengu.redp.hawk.service.HawkMonitorConfigService;
import cc.rengu.redp.hawk.service.HawkMonitorService;
import com.alibaba.fastjson.JSONArray;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xushitang
 */
@RestController
@RequestMapping("/hawk/show")
public class HawkMonitorShowController {

    @Autowired
    private HawkMonitorConfigService hawkMonitorConfigService;
    @Autowired
    private HawkMonitorService hawkMonitorService;

    @GetMapping
    public Map<String, List<HawkMonitorShow>> getAllGraph() {
        Map<String, List<HawkMonitorShow>> sortedMap = new LinkedHashMap<>();
        Map<String, List<HawkMonitorShow>> unsortedMap = hawkMonitorConfigService.getGraphToShow().stream()
                .collect(Collectors.groupingBy(HawkMonitorShow::getShowGroupName));
        /**
         * 从未排序的Map转化为已排序的Map
         * 分组是形如"10-组名1"、"11-组名2"的字符串，此处按前缀排序，并去除排序前缀号
         */
        unsortedMap.keySet().stream()
                .sorted(Comparator.comparing(i -> Integer.valueOf(i.split("-")[0])))
                .forEach(u -> sortedMap.put(u.split("-")[1], unsortedMap.get(u)));
        return sortedMap;
    }

    @GetMapping("/data")
    public List<GraphData> getGraph(@ApiParam(required = true, value = "json格式字符串参数")String graphDataQueryString) {
        List<GraphDataQuery> graphDataQueries = JSONArray.parseArray(graphDataQueryString, GraphDataQuery.class);
        return graphDataQueries.stream().map(g -> this.hawkMonitorService.getData(g)).collect(Collectors.toList());
    }
}
